//
//  ImageDetailViewController.m
//  reacticons
//
//  Created by Nong Nghia on 6/22/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ImageDetailViewController.h"
#import "ImageScrollView.h"
#import "DownloadHelper.h"
#import "Utilities.h"

#import <FacebookSDK/FacebookSDK.h>
#import <Twitter/Twitter.h>

#import "AppDelegate.h"
#import "CropImageView.h"
#import "MemeCreatorViewController.h"
#import <QuartzCore/QuartzCore.h>

#import "Photo.h"
#import "DatabaseConnection.h"
#import "LoadingView.h"
#import "CMCFBShareViewController.h"

#define MAX_HIGHT 460.0
#define MAX_WIDTH 320.0

#define PADDING  15
#define FAVORITE_TAG 11
#define MEME_TAG 12
#define EDIT_TAG 13
#define EXPORT_TAG 14
#define DELETE_TAG 15

#define CROP_IMAGE_TAG -1
#define SAVE_IMAGE_TAG 32
#define CANCEL_IMAGE_TAG 31
#define ROTATE_IMAGE_TAG -1
#define SHARE_BTN_TAG 21

#define FAVORITE_TYPE @"favorite"
#define ITEM_TYPE @"item"
#define MEME_TYPE @"meme"

#define PLACEHOLDER_TXT @"Type your comment here..."
#define MAX_LENGTH 255

@interface ImageDetailViewController (internal)

- (void)updateCurrentView;
- (void)startFB;
- (void)startTwitter;
- (void)sendMail;
- (void)postImageToAlbum:(UIImage *)image;
- (void)sendStatus;

@end

@implementation ImageDetailViewController

@synthesize itemList;
@synthesize itemIndex;
@synthesize itemType;

#pragma mark - View Life Cycle

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

-(void)configureView{
    self.title=[NSString stringWithFormat:@"%d of %d",itemIndex+1,itemList.count];
    [pagingScrollView setContentSize:[self contentSizeForPagingScrollView]];
    [recycledPages removeAllObjects];
    [visiblePages removeAllObjects];
    [recycledPages release];
    recycledPages=nil;
    [visiblePages release];
    visiblePages=nil;
    recycledPages = [[NSMutableSet alloc] init];
    visiblePages  = [[NSMutableSet alloc] init];
    if (itemIndex==0) {
        [self tilePages];
    }
    else {
        [pagingScrollView scrollRectToVisible:CGRectMake(320*itemIndex+PADDING*2*(itemIndex+1),0, 320, 460) animated:NO];
    }
    
    Photo * photo = [itemList objectAtIndex:itemIndex];
    if ([Utilities checkFavoriteAdded:[photo.photoImage lastPathComponent]]) {
        [deleteBtn setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
        [addToFavoriteButton setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
    }
    else
    {
        [deleteBtn setImage:[UIImage imageNamed:@"star.png"]];
        [addToFavoriteButton setImage:[UIImage imageNamed:@"star.png"]];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([itemType isEqualToString:MEME_TYPE]) {
        [deleteBtn setTag:1];
    }
    if ([itemType isEqualToString:FAVORITE_TYPE]) {
        NSMutableArray *arr=[[NSMutableArray alloc] initWithArray:[utilitiesToolbar items]];
        [arr removeObjectAtIndex:6];
        [arr removeObjectAtIndex:5];
        [utilitiesToolbar setItems:arr];

    }
    inputMeme=[[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
    
    UIBarButtonItem *shareBtn=[[UIBarButtonItem alloc] initWithTitle:@"Share" style:UIBarButtonItemStyleBordered target:self action:@selector(btnWasClicked:)];
    [shareBtn setTag:21];
    [self.navigationItem setRightBarButtonItem:shareBtn];
    [shareBtn release];
//    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackTranslucent];

    pagingScrollView=[[UIScrollView alloc] initWithFrame:[self frameForPagingScrollView]];
    pagingScrollView.pagingEnabled = YES;
    pagingScrollView.backgroundColor = [UIColor blackColor];
    pagingScrollView.showsVerticalScrollIndicator = NO;
    pagingScrollView.showsHorizontalScrollIndicator = NO;
    pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
    pagingScrollView.delegate = self;
//    [pagingScrollView setDelaysContentTouches:YES];
    [self.view insertSubview:pagingScrollView atIndex:0];

    
    [self configureView];
    
    
    
    isFullScreen=NO;

    [editingToolbar setHidden:YES];
    isEditing=NO;
    
    if ([itemType isEqualToString:@"item"]) {
        [favouriteToolbar setHidden:NO];
        [utilitiesToolbar setHidden:YES];
    }
    else {
        [favouriteToolbar setHidden:YES];
        [utilitiesToolbar setHidden:NO];
    }
    
    popupLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 40)];
    [popupLabel setText:@"Image Copied!"];
    [popupLabel setFont:[UIFont fontWithName:@"Helvetica" size:14]];
    [popupLabel setTextColor:[UIColor whiteColor]];
    [popupLabel setTextAlignment:UITextAlignmentCenter];
    [popupLabel setBackgroundColor:[UIColor blackColor]];
    popupLabel.layer.borderColor=[UIColor whiteColor].CGColor;
    popupLabel.layer.borderWidth=2;
    popupLabel.layer.cornerRadius=10;
    [popupLabel setHidden:YES];
    [self.view addSubview:popupLabel];
    [popupLabel setCenter:CGPointMake(self.view.center.x, self.view.center.y+100)];
    
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [favouriteToolbar setHidden:YES];
    if ([itemType isEqualToString:@"item"]) {
        [favouriteToolbar setHidden:NO];
        [utilitiesToolbar setHidden:YES];
    }
    else {
        [favouriteToolbar setHidden:YES];
        [utilitiesToolbar setHidden:NO];
    }
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackTranslucent];

    [Utilities hideTabBar:nil];
    if (![DatabaseConnection isAddedToFavoriteWithPhotoID:[(Photo*)[itemList objectAtIndex:itemIndex] photoID]]) {
        [deleteBtn setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
        [addToFavoriteButton setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
    }
    else {
        [deleteBtn setImage:[UIImage imageNamed:@"star.png"]];
        [addToFavoriteButton setImage:[UIImage imageNamed:@"star.png"]];
    }
    
    
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if ([itemType isEqualToString:@"item"]) {
        [favouriteToolbar setHidden:NO];
        [utilitiesToolbar setHidden:YES];
    }
    else {
        [favouriteToolbar setHidden:YES];
        [utilitiesToolbar setHidden:NO];
    }
    [Utilities hideTabBar:nil];
    if (![DatabaseConnection isAddedToFavoriteWithPhotoID:[(Photo*)[itemList objectAtIndex:itemIndex] photoID]]) {
        [deleteBtn setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
        [addToFavoriteButton setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
    }
    else {
        [deleteBtn setImage:[UIImage imageNamed:@"star.png"]];
        [addToFavoriteButton setImage:[UIImage imageNamed:@"star.png"]];
    }
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [pagingScrollView release];
    pagingScrollView = nil;
    [recycledPages release];
    recycledPages = nil;
    [visiblePages release];
    visiblePages = nil;


}


- (void)dealloc
{
    [pagingScrollView release];
    [super dealloc];
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



#pragma mark - -------------------------------START-------------------------------------


#pragma mark -
#pragma mark Tiling and page configuration

- (void)tilePages 
{
//    DBLOG(@"PhotoViewController - tilePages");
    // Calculate which pages are visible
    CGRect visibleBounds = pagingScrollView.bounds;
    int firstNeededPageIndex = floorf(CGRectGetMinX(visibleBounds) / CGRectGetWidth(visibleBounds));
    int lastNeededPageIndex  = floorf((CGRectGetMaxX(visibleBounds)-1) / CGRectGetWidth(visibleBounds));
    firstNeededPageIndex = MAX(firstNeededPageIndex, 0);
    lastNeededPageIndex  = MIN(lastNeededPageIndex, itemList.count - 1);
    
    // Recycle no-longer-visible pages 
    for (ImageScrollView *page in visiblePages) {
        if (page.index < firstNeededPageIndex || page.index > lastNeededPageIndex) {
//            DBLOG(@"recycle nologer visible:%d",page.index);
            [recycledPages addObject:page];
            [page removeFromSuperview];
        }
    }
    [visiblePages minusSet:recycledPages];
    
    // add missing pages
    for (int index = firstNeededPageIndex; index <= lastNeededPageIndex; index++) {

        if (![self isDisplayingPageForIndex:index]) {
//            DBLOG(@"AddMissingPage:%d",index);
            ImageScrollView *page = [self dequeueRecycledPage];
            if (page == nil) {
                page = [[[ImageScrollView alloc] init] autorelease];
            }
            [self configurePage:page forIndex:index];
            [pagingScrollView addSubview:page];
            [visiblePages addObject:page];
        }
        else {
//            DBLOG(@"PhotoViewController - tilePages - current index:%d",index);
            itemIndex=index;
            self.title=[NSString stringWithFormat:@"%d of %d",itemIndex+1,itemList.count];
            
            if (![DatabaseConnection isAddedToFavoriteWithPhotoID:[(Photo*)[itemList objectAtIndex:itemIndex]photoID]]) {
                [addToFavoriteButton setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
                [deleteBtn setImage:[UIImage imageNamed:@"fav_star_empty.png"]];

            }
            else {
                [deleteBtn setImage:[UIImage imageNamed:@"star.png"]];
                [addToFavoriteButton setImage:[UIImage imageNamed:@"star.png"]];
            }

        }
    }    
}

- (ImageScrollView *)dequeueRecycledPage
{
//    DBLOG(@"PhotoViewController - dequeueRecycledPage");
    ImageScrollView *page = [recycledPages anyObject];
    if (page) {
        [[page retain] autorelease];
        [recycledPages removeObject:page];
    }
    return page;
}

- (BOOL)isDisplayingPageForIndex:(NSUInteger)index
{
    BOOL foundPage = NO;
    for (ImageScrollView *page in visiblePages) {
        if (page.index == index) {
            foundPage = YES;
            break;
        }
    }
    return foundPage;
}

- (void)configurePage:(ImageScrollView *)page forIndex:(NSUInteger)index
{
//    DBLOG(@"PhotoViewController - configurePage - forindex:%d",index);
    page.index = index;
    page.frame = [self frameForPageAtIndex:index];
    
    [page displayImage:[self imageAtIndex:index]];
    UITapGestureRecognizer *tapges=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureDidReceived:)];
//    [tapges setDelaysTouchesBegan:YES];
    [tapges setNumberOfTapsRequired:1];
//    [page setGestureRecognizers:[NSArray arrayWithObjects:tapges, nil]];
    [tapges release];
    
}

#pragma mark -
#pragma mark ScrollView delegate methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!isEditing) {
        [self tilePages];
 
    }
    else {
        [pagingScrollView setContentOffset: CGPointMake(320*itemIndex+PADDING*2*(itemIndex), 0)];
    }
}

#pragma mark -
#pragma mark View controller rotation methods


- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    // here, our pagingScrollView bounds have not yet been updated for the new interface orientation. So this is a good
    // place to calculate the content offset that we will need in the new orientation
    CGFloat offset = pagingScrollView.contentOffset.x;
    CGFloat pageWidth = pagingScrollView.bounds.size.width;
    
    if (offset >= 0) {
        firstVisiblePageIndexBeforeRotation = floorf(offset / pageWidth);
        percentScrolledIntoFirstVisiblePage = (offset - (firstVisiblePageIndexBeforeRotation * pageWidth)) / pageWidth;
    } else {
        firstVisiblePageIndexBeforeRotation = 0;
        percentScrolledIntoFirstVisiblePage = offset / pageWidth;
    }    
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    DBLOG(@"PhotoViewController - willAnimateRotationToInterfaceOrientation - duration:%f",duration);

    // recalculate contentSize based on current orientation
    pagingScrollView.contentSize = [self contentSizeForPagingScrollView];
    
    // adjust frames and configuration of each visible page
    for (ImageScrollView *page in visiblePages) {
        CGPoint restorePoint = [page pointToCenterAfterRotation];
        CGFloat restoreScale = [page scaleToRestoreAfterRotation];
        page.frame = [self frameForPageAtIndex:page.index];
        [page setMaxMinZoomScalesForCurrentBounds];
        [page restoreCenterPoint:restorePoint scale:restoreScale];
        
    }
    
    // adjust contentOffset to preserve page location based on values collected prior to location
    CGFloat pageWidth = pagingScrollView.bounds.size.width;
    CGFloat newOffset = (firstVisiblePageIndexBeforeRotation * pageWidth) + (percentScrolledIntoFirstVisiblePage * pageWidth);
    pagingScrollView.contentOffset = CGPointMake(newOffset, 0);
}

#pragma mark -
#pragma mark  Frame calculations

- (CGRect)frameForPagingScrollView {
    CGRect frame = [[UIScreen mainScreen] bounds];
    frame.origin.x -= PADDING;
    frame.size.width += (2 * PADDING);
    return frame;
}

- (CGRect)frameForPageAtIndex:(NSUInteger)index {
//    DBLOG(@"PhotoViewController - frameForPageAtIndex:%d",index);
    
    CGRect bounds = pagingScrollView.bounds;
    CGRect pageFrame = bounds;
    pageFrame.size.width -= (2 * PADDING);
    pageFrame.origin.x = (bounds.size.width * index) + PADDING;
    return pageFrame;
}

- (CGSize)contentSizeForPagingScrollView {
    // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above.
    CGRect bounds = pagingScrollView.bounds;
    //    bounds.size.height
    return CGSizeMake(bounds.size.width * itemList.count, 460.0);
}


#pragma mark -
#pragma mark Image wrangling


- (UIImage *)imageAtIndex:(NSUInteger)index {

//    DBLOG(@"PhotoViewController - imageAtIndex:%d",index);
    Photo *photo = [itemList objectAtIndex:index];
    
    NSFileManager *fm=[[NSFileManager alloc] init];
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *targetPath= nil;
    
    if ([itemType isEqualToString:@"item"]||[itemType isEqualToString:@"favorite"]) {
        targetPath=[documentPath retain];
        
        if ([fm fileExistsAtPath:[targetPath stringByAppendingPathComponent:[[photo photoImage] lastPathComponent]]]) {
            
            return [UIImage imageWithContentsOfFile:[targetPath stringByAppendingPathComponent:[photo.photoImage lastPathComponent]]];
            
        }
        else {
            //call download image here

            [[NSNotificationCenter defaultCenter] addObserver:self 
                                                     selector:@selector(downloadImageFinish:) 
                                                         name:[NSString stringWithFormat:@"DetailSuccess|%@",[photo.photoImage lastPathComponent]]
                                                       object:nil];
            
            
            [[NSNotificationCenter defaultCenter] addObserver:self
                                                     selector:@selector(downloadImageFail:)
                                                         name:[NSString stringWithFormat:@"DetailFail|%@",[photo.photoImage lastPathComponent]]
                                                       object:nil];
            
            DownloadHelper *dhelper=[[DownloadHelper alloc] init];
            [dhelper downloadFile:[photo.photoImage lastPathComponent] toFolderWithName:nil
                          withURL:[NSURL URLWithString:photo.photoImage]   
           andSuccessNotification:[NSString stringWithFormat:@"DetailSuccess|%@",[photo.photoImage lastPathComponent]]
              andFailNotification:[NSString stringWithFormat:@"DetailFail|%@",[photo.photoImage lastPathComponent]]];

            return nil;

        }
    }
    else {

        targetPath=[[documentPath stringByAppendingPathComponent:@"Meme"] retain];
        return [UIImage imageWithContentsOfFile:[targetPath stringByAppendingPathComponent:[photo.photoImage lastPathComponent]]];

    }
}

- (UIImage *)imageInScrollViewAtIndex:(NSUInteger)index {
    
    for (ImageScrollView *item in visiblePages) {
        if (item.index==itemIndex && [item.imageView isKindOfClass:[UIImageView class]]) {
            return [(UIImageView*)item.imageView image];
        }
    }
    return nil;
}

- (NSString *)imageNameAtIndex:(NSUInteger)index {
    NSString *name = nil;
    if (index < itemList.count) {
        name = [[(Photo*)[itemList objectAtIndex:index] photoImage] lastPathComponent];
    }
    return name;
}

- (CGSize)imageSizeAtIndex:(NSUInteger)index {
    return [[self imageAtIndex:index] size];
}




#pragma mark - ----------------------------------------END-------------------------------------------

#pragma mark - update view



-(void)downloadImageFinish:(NSNotification*)notification{
    DBLOG(@"ImageDetailViewController - downloadImageFinish:%@",[notification object]);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notification.name object:nil];
        for (ImageScrollView *page in visiblePages) {
            if ([self isDisplayingPageForIndex:page.index]){
                [page displayImage:[self imageAtIndex:page.index]];
            }
    }
}
-(void)downloadImageFail:(NSNotification*)notification{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:notification.name object:nil];
    DBLOG(@"ImageDetailViewController - downloadImageFail:%@",[notification object]);

}


-(IBAction)btnWasClicked:(id)sender
{
    if (![self imageInScrollViewAtIndex:itemIndex]) {
        return;
    }
    DBLOG(@"%d",[sender tag]);
    if ([sender tag]==1)    // request save to Favorites folder
    {
        Photo *photo=(Photo*)[itemList objectAtIndex:itemIndex];
        if ([DatabaseConnection isAddedToFavoriteWithPhotoID:photo.photoID]) {
            [addToFavoriteButton setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
            [deleteBtn setImage:[UIImage imageNamed:@"fav_star_empty.png"]];
            [DatabaseConnection deleteListItems:[NSMutableArray arrayWithObject:[photo itemObject]] fromEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
        }
        else {
            DBLOG(@"Add to Favorites:%d",itemIndex);
            if ([itemType isEqualToString:@"meme"]) {
                [photo setPhotoCreatedDate:[Utilities uniqueStringWithPrefix:@""]];
                [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[photo itemObject]] toEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
                [deleteBtn setImage:[UIImage imageNamed:@"star.png"]];
            }
            else {
                [photo setPhotoCreatedDate:[Utilities uniqueStringWithPrefix:@""]];
                [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[photo itemObject]] toEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
                [addToFavoriteButton setImage:[UIImage imageNamed:@"star.png"]];

            }
            return;
        }
        
    }
    
    if([sender tag]==FAVORITE_TAG){
        Photo *photo=(Photo*)[itemList objectAtIndex:itemIndex];

        [DatabaseConnection deleteListItems:[NSMutableArray arrayWithObject:[photo itemObject]] fromEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];


        
        itemList=[[DatabaseConnection getFavoritePhotos] retain];
        if (itemList.count==0) {
            DBLOG(@"DIE");
            [self.navigationController setNavigationBarHidden:NO];
            [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
            [self.navigationController popViewControllerAnimated:YES];
            [Utilities showTabBar:self.tabBarController];
            return;
        }
        else {
            DBLOG(@"OK");
        }
        itemIndex=(itemIndex>itemList.count-1)?itemList.count-1:itemIndex;
        for (UIView *view in pagingScrollView.subviews) {
            [view removeFromSuperview];
        }
        [self configureView];
        [self tilePages];
        [self reloadInputViews];
        
    }
    if([sender tag]==MEME_TAG){
       
        MemeCreatorViewController *mcvc=[[MemeCreatorViewController alloc] init];
        [mcvc setImage:[self imageInScrollViewAtIndex:itemIndex]];
        [self presentModalViewController:mcvc animated:YES];
        
    }
    if([sender tag]==EDIT_TAG){
        UIActionSheet *actionSheet=[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:
                                    @"Rotate Image",
                                    @"Crop Image",
                                    nil];
        [actionSheet setTag:EDIT_TAG];
        [actionSheet showInView:self.view];
        [actionSheet release];
    }
    if([sender tag]==EXPORT_TAG){
        UIActionSheet *actionSheet=[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:
                                    @"Export To Phone Gallery",
                                    nil];
        [actionSheet setTag:EXPORT_TAG];
        [actionSheet showInView:self.view];
        [actionSheet release];
    }
    
    if ([sender tag]==21) {
        UIActionSheet *actionSheet=[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:
                                    @"Email Reacticon",
                                    @"Copy For Messaging", 
                                    @"Assign To Contact", 
                                    @"Facebook", 
                                    @"Twitter", 
                                    nil];
        [actionSheet setTag:21];
        [actionSheet showInView:self.view];
        [actionSheet release];
        return;
    }
    if ([sender tag]==CANCEL_IMAGE_TAG) {
        [cropView removeFromSuperview];
        [utilitiesToolbar setHidden:NO];
        [deleteBtn setEnabled:YES];
        [exportBtn setEnabled:YES];
        isEditing=NO;
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [editingToolbar setHidden:YES];
        for (ImageScrollView *view in pagingScrollView.subviews) {
            if ([(ImageScrollView*)view index]==itemIndex) {
                [(ImageScrollView*)view displayImage:[self imageAtIndex:itemIndex]];
            }
        }
        
        return;
    }
    
    if ([sender tag]==SAVE_IMAGE_TAG) {
        if (isCropping) {
            saveBtn.title=@"Save";
            isCropping=NO;
            [utilitiesToolbar setHidden:NO];
            for (ImageScrollView *view in pagingScrollView.subviews) {
                if ([(ImageScrollView*)view index]==itemIndex) {
                    [(ImageScrollView*)view displayImage:[Utilities cropImage:((UIImageView*)[view.subviews objectAtIndex:0]).image 
                                                                     withRect:[cropView cropSize]]];
                }
            }
            [cropView removeFromSuperview];
            return;
        }

        [deleteBtn setEnabled:YES];
        [exportBtn setEnabled:YES];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [editingToolbar setHidden:YES];
        
    

        for (ImageScrollView *view in pagingScrollView.subviews) {
            if ([(ImageScrollView*)view index]==itemIndex) {
                Photo *photo=[itemList objectAtIndex:itemIndex];
//                UIImage *img=[[UIImage alloc] initWithCGImage:((UIImageView*)[view.subviews objectAtIndex:0]).image.CGImage];
                [DatabaseConnection updateToCustomPhoto:photo withImage:((UIImageView*)[view.subviews objectAtIndex:0]).image];
            }
        }
        isEditing=NO;

        /*
        if ([itemType isEqualToString:@"meme"]) {
            itemList=[[DatabaseConnection getCustomsPhotos] retain];
        }
        else{
            itemList=[[DatabaseConnection getFavoritePhotos] retain];

        }
//        itemIndex=(itemIndex>itemList.count-1)?itemList.count-1:itemIndex;
        for (UIView *view in pagingScrollView.subviews) {
            [view removeFromSuperview];
        }
        itemIndex=0;
        [pagingScrollView setContentOffset:CGPointMake(0, 0)];
        isEditing=NO;
        [self configureView];
        [self reloadInputViews];
         */
        return;
    }
    
}

#pragma mark - Action Sheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    DBLOG(@"actionsheet:%d|%d",[actionSheet tag],buttonIndex);
    if ([actionSheet tag]==MEME_TAG) {
        if (buttonIndex==2) {
            return;
        }
        inputMeme = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 45.0, 260.0, 25.0)];
        [inputMeme setBackgroundColor:[UIColor whiteColor]];
        [inputMeme becomeFirstResponder];
        [inputMeme setAutocorrectionType:UITextAutocorrectionTypeNo];
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Add Text" message:@"  " delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        [alert setTag:MEME_TAG*10+buttonIndex];
        [alert addSubview:inputMeme];
        [alert show];
        [alert release];

    }
       
    if ([actionSheet tag]==EDIT_TAG) {
        if (buttonIndex==0) {
            UIActionSheet *actionSheet=[[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:
                                        @"Rotate 90",
                                        @"Rotate 180",
                                        @"Rotate -90",
                                        nil];
            [actionSheet setTag:16];
            [actionSheet showInView:self.view];
            [actionSheet release];
        }
        if (buttonIndex==1) {
            saveBtn.title=@"Crop";
            isCropping=YES;
            isEditing=YES;
            [editingToolbar setHidden:NO];
            [utilitiesToolbar setHidden:YES];
            [deleteBtn setEnabled:NO];
            [exportBtn setEnabled:NO];
            
            [self.navigationController setNavigationBarHidden:YES animated:NO];
            
            for (ImageScrollView *icv in visiblePages) {
                if (icv.index == itemIndex) {
                    
                    [cropView removeFromSuperview];
                    cropView=nil;
                    cropView = [[CropImageView alloc] initWithFrame:icv.imageView.frame];
                    [cropView setZoomRatio:(((UIImageView*)[icv.subviews objectAtIndex:0]).image).size.width/icv.imageView.frame.size.width];
                    [self.view bringSubviewToFront:cropView];
                    [self.view addSubview:cropView];
                    break;
                }
                
            }
            
            [self.view bringSubviewToFront:editingToolbar];
            
            
        }  

    }
    if ([actionSheet tag]==EXPORT_TAG) {
        if (buttonIndex==0) {
            UIImageWriteToSavedPhotosAlbum([self imageInScrollViewAtIndex:itemIndex], nil,nil,nil);
            
            [self.view bringSubviewToFront:popupLabel];
            [popupLabel setHidden:NO];
            [popupLabel performSelector:@selector(setHidden:) withObject:[NSNumber numberWithInt:1] afterDelay:2];
            
        }
    }
    
    if ([actionSheet tag]==DELETE_TAG) {
        if (buttonIndex==0) {
            NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
            NSString *favoritePath=[documentPath stringByAppendingPathComponent:@"Favorites"];
            NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];            
            [fm removeItemAtPath:[favoritePath stringByAppendingPathComponent:[[(Photo*)[itemList objectAtIndex:itemIndex] photoImage] lastPathComponent]] error:nil];

//            [Utilities deleteFileAtURL:[NSURL URLWithString:[(Items*)[itemList objectAtIndex:itemIndex] image]]];
            itemList=[[DatabaseConnection getFavoritePhotos] retain];
            
            itemIndex=(itemIndex>itemList.count-1)?itemList.count-1:itemIndex;
            for (UIView *view in pagingScrollView.subviews) {
                [view removeFromSuperview];
            }
            [self configureView];
            [self tilePages];
            [self reloadInputViews];
            
        }
        return;
    }

    if ([actionSheet tag]==16) {
        if (buttonIndex==3) {
            return;
        }

        for (ImageScrollView *view in pagingScrollView.subviews) {
            if ([(ImageScrollView*)view index]==itemIndex) {
                isEditing=YES;
                [editingToolbar setHidden:NO];
                [deleteBtn setEnabled:NO];
                [exportBtn setEnabled:NO];
                [self.navigationController setNavigationBarHidden:YES animated:NO];

                switch (buttonIndex) {
                    case 0:
                        [(ImageScrollView*)view displayImage:[Utilities rotateImage:((UIImageView*)[view.subviews objectAtIndex:0]).image 
                                                                    withOrientation:UIImageOrientationLeft]];
                        break;
                    case 1:
                        [(ImageScrollView*)view displayImage:[Utilities rotateImage:((UIImageView*)[view.subviews objectAtIndex:0]).image 
                                                                    withOrientation:UIImageOrientationDown]];
                        break;
                    case 2:
                        [(ImageScrollView*)view displayImage:[Utilities rotateImage:((UIImageView*)[view.subviews objectAtIndex:0]).image 
                                                                    withOrientation:UIImageOrientationRight]];
                        break;
                    default:
                        break;
                }

                return;
            }
        }

        
    }
    
    
    if ([actionSheet tag]==21) {
        if (buttonIndex==0){
            DBLOG(@"Email Reacticons");
            [self sendMail];
        }
        else if(buttonIndex==1) {
            DBLOG(@"Copy and Messaging");
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.image = [self imageInScrollViewAtIndex:itemIndex];
            
            UIAlertView * copyToClipboardAlert = [[[UIAlertView alloc] initWithTitle:@"" message:@"Reaction copied to clipboard! Do you want to open a text?\n(remember to paste the image!)" delegate:self cancelButtonTitle:@"No" otherButtonTitles:@"Open Text", nil] autorelease];
            
            [copyToClipboardAlert setTag:2];
            [copyToClipboardAlert show];
//            [copyToClipboardAlert release];
        }
        else if(buttonIndex==2) {
            DBLOG(@"Assign To Contact");
            ABPeoplePickerNavigationController *picker =[[ABPeoplePickerNavigationController alloc] init];
            picker.peoplePickerDelegate = self;
            
            [self presentModalViewController:picker animated:YES];
        }
        else if(buttonIndex==3) {
            DBLOG(@"Facebook");
            [self startFB];
        }
        else if(buttonIndex==4) {
            DBLOG(@"Twitter");
            [self startTwitter];
        }
        else if(buttonIndex==5) {
            DBLOG(@"Cancel");

        }
    }
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    DBLOG(@"alertview delegate:%d|%d",[alertView tag],buttonIndex);
    if (buttonIndex==0) {
        return;
    }
    
    if (alertView.tag == 2) {
        if (buttonIndex==1) {
            NSString *stringURL = @"sms:";
            NSURL *url = [NSURL URLWithString:stringURL];
            [[UIApplication sharedApplication] openURL:url]; 
            return;
        }

    }
    
    // WRITE MEME TO TOP
    if ([alertView tag]==MEME_TAG*10) {
        
        for (ImageScrollView *view in pagingScrollView.subviews) {
            if ([(ImageScrollView*)view index]==itemIndex) {
                if (![itemType isEqualToString:@"item"]) {
                    isEditing=YES;
                    [editingToolbar setHidden:NO];
                    [deleteBtn setEnabled:NO];
                    [exportBtn setEnabled:NO];
                    [self.navigationController setNavigationBarHidden:YES animated:NO];
                }
                [(ImageScrollView*)view displayImage:[Utilities createMeme:inputMeme.text 
                                                                 withImage:((UIImageView*)[view.subviews objectAtIndex:0]).image 
                                                                     atTop:YES]];

                return;
            }
        }
    }
    
    //WRITE MEME TO BOTTOM
    if ([alertView tag]==MEME_TAG*10+1) {
        for (ImageScrollView *view in pagingScrollView.subviews) {
            if ([(ImageScrollView*)view index]==itemIndex) {
                if (![itemType isEqualToString:@"item"]) {
                    isEditing=YES;
                    [editingToolbar setHidden:NO];
                    [deleteBtn setEnabled:NO];
                    [exportBtn setEnabled:NO];
                    [self.navigationController setNavigationBarHidden:YES animated:NO];
                }
        
                [(ImageScrollView*)view displayImage:[Utilities createMeme:inputMeme.text withImage:((UIImageView*)[view.subviews objectAtIndex:0]).image 
                                                                     atTop:NO]];
                return;
            }
        }
    }
}

#pragma mark - Gesture Recognize
-(void)gestureDidReceived:(UIGestureRecognizer*)gesture{
    if (isEditing) {
        return;
    }

    
    if ([gesture isKindOfClass:[UITapGestureRecognizer class]]) {
        if ([(UITapGestureRecognizer*)gesture numberOfTapsRequired]!=1) {
            return;
        }
        else{
            if (isFullScreen) {
                isFullScreen=NO;
                [self.navigationController setNavigationBarHidden:NO animated:YES];
                if ([itemType isEqualToString:@"item"]) {
                    [favouriteToolbar setHidden:NO];
                    [utilitiesToolbar setHidden:YES];
                }
                else {
                    [favouriteToolbar setHidden:YES];
                    [utilitiesToolbar setHidden:NO];
                }
            }
            else {
                isFullScreen=YES;
                [favouriteToolbar setHidden:YES];
                [utilitiesToolbar setHidden:YES];
                [self.navigationController setNavigationBarHidden:YES animated:YES];
            }
        }
       
        
    }
 
}

#pragma mark -
#pragma mark Facbook Delegate
#pragma mark - ------------facebook---------------
-(void)startFB{
    CMCFBShareViewController *cfsVC=[[CMCFBShareViewController alloc] init];
    [cfsVC setImage:[self imageInScrollViewAtIndex:itemIndex]];
    [CMCFBShareViewController presentViewController:cfsVC];
}

#pragma mark - ------Email delegate-----
-(void)sendMail{
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
        picker.mailComposeDelegate = self;
//        [picker setSubject:@"Email"];
        
        // Fill out the email body text
//        NSString *pageLink = @"http://www.reacticons.com"; // replace it with yours
        NSString *iTunesLink = @"itms-apps://itunes.com/apps/reacticons"; // replate it with yours
        NSString *emailBody =
        [NSString stringWithFormat:@"\n<p>Sent from Reacticons! ...an gallery app of all reaction images.</br> <a href = '%@'>Download</a> it now!</p>", iTunesLink];
        
        [picker setMessageBody:emailBody isHTML:YES];
        picker.navigationBar.barStyle = UIBarStyleBlack;
        
        [picker setDelegate:self];
        
        [picker setMailComposeDelegate:self];
        UIImage *emailImage = [self imageInScrollViewAtIndex:itemIndex];
        
        NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];
        
        [picker addAttachmentData:imageData mimeType:@"png" fileName:[[(Photo*)[itemList objectAtIndex:itemIndex] photoImage] lastPathComponent]];
        
        [self presentModalViewController:picker animated:YES];
        [picker release];
        
    }
    
    else {
        
        DBLOG(@"Device is unable to send email in its current state.");
        
    }
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    [self dismissModalViewControllerAnimated:YES];

    
}
#pragma mark - ----------Twitter ---------------
-(void)startTwitter{
	
    if ([TWTweetComposeViewController canSendTweet]) {
        TWTweetComposeViewController *tweet=[[TWTweetComposeViewController alloc] init];
        [tweet setInitialText:@"#reacticons "];
//        [tweet addURL:[NSURL URLWithString:@"http://itunes.com/apps/reacticons"]];
        [tweet addImage:[self imageInScrollViewAtIndex:itemIndex]];
        [tweet setCompletionHandler:^(TWTweetComposeViewControllerResult result){
            [self dismissModalViewControllerAnimated:YES];
            switch (result) {
                case TWTweetComposeViewControllerResultDone:
                    DBLOG(@"Done");
                    break;
                case TWTweetComposeViewControllerResultCancelled:
                    DBLOG(@"Cancel");
                    break;
                default:
                    break;
            }
            
        }];
        [self presentModalViewController:tweet animated:YES];
        [tweet release];
    }
    else{
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"  "
                                                       message:@"Please login to Twitter Account in Setting or in Twitter Application before sharing!"
                                                      delegate:nil
                                             cancelButtonTitle:@"OK"
                                             otherButtonTitles:  nil];
        [alert show];
        [alert release];
    }

}

#pragma mark - peoplePicker Delegate

- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
    [peoplePicker dismissModalViewControllerAnimated:YES];
}

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{
    ABAddressBookRef addressBook =ABAddressBookCreate();
    ABRecordRef newRecord=ABAddressBookGetPersonWithRecordID(addressBook, ABRecordGetRecordID(person));
    
    NSData *imageData = [NSData dataWithData:UIImageJPEGRepresentation([self imageInScrollViewAtIndex:itemIndex], 1)];
    CFDataRef imgDataRef = (CFDataRef)imageData;
    CFErrorRef error=NULL;
    if(ABPersonSetImageData( newRecord,  imgDataRef, &error)){
        DBLOG(@"set image success:%@,",person);
    }
    else {
        DBLOG(@"set image fail");
        
    }
    
    error=NULL;
    BOOL didSave;
    if (ABAddressBookHasUnsavedChanges(addressBook)) 
    {
        didSave = ABAddressBookSave(addressBook, &error);
        if (!didSave) {
            DBLOG(@"cannot save");
        }
        else {
            DBLOG(@"save success");
        }
    }
    else {
        DBLOG(@"addressbook no change");
    }
    
    CFRelease(addressBook);
    
    [peoplePicker dismissModalViewControllerAnimated:YES];
    return NO;
}

#pragma mark - Hide Tabbar

@end
